<!-- src/main/resources/templates/invitation-page.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>接受邀请 - 时光胶囊</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; }
        .container { background: white; padding: 40px; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); max-width: 500px; width: 100%; }
        .btn { background: #007bff; color: white; padding: 12px 24px; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; margin: 10px; }
        .btn-secondary { background: #6c757d; }
        .message { padding: 15px; border-radius: 8px; margin: 20px 0; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .warning { background: #fff3cd; color: #856404; border: 1px solid #ffeaa7; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
    </style>
</head>
<body>
<div class="container">
    <h2>📨 时光胶囊邀请</h2>

    <!-- 已登录但账号不匹配的情况 -->
    <div th:if="${isLoggedIn and intendedRecipient != userPhone}">
        <div class="message warning">
            <h4>账号不匹配</h4>
            <p>此邀请是发给 <strong th:text="${intendedRecipient}"></strong> 的</p>
            <p>当前登录账号: <strong th:text="${userPhone}"></strong></p>
        </div>
        <button class="btn" onclick="switchAccount()">切换到正确账号</button>
        <button class="btn btn-secondary" onclick="ignoreInvitation()">忽略邀请</button>
    </div>

    <!-- 已登录且账号匹配的情况 -->
    <div th:if="${isLoggedIn and intendedRecipient == userPhone}">
        <div class="message success">
            <h4>✅ 邀请待接受</h4>
            <p>发送者: <strong th:text="${senderPhone}"></strong></p>
            <p>胶囊标题: <strong th:text="${capsuleTitle}"></strong></p>
        </div>
        <button class="btn" onclick="acceptInvitation()">立即接受</button>
    </div>

    <!-- 未登录的情况 -->
    <div th:unless="${isLoggedIn}">
        <div class="message info">
            <h4>🔐 请先登录</h4>
            <p>邀请接收人: <strong th:text="${intendedRecipient}"></strong></p>
            <p>请登录以接受时光胶囊邀请</p>
        </div>
        <button class="btn" onclick="redirectToLogin()">立即登录</button>
    </div>
</div>

<script th:inline="javascript">
    /*<![CDATA[*/
    const token = [[${token}]];
    const intendedRecipient = [[${intendedRecipient}]];
    const senderPhone = [[${senderPhone}]];
    const capsuleTitle = [[${capsuleTitle}]];

    function redirectToLogin() {
    // 先清除当前登录状态
    fetch('/api/auth/logout', {
        method: 'POST',
        credentials: 'include' // 如果你使用了 cookie 认证
    }).catch(err => console.log("退出失败，直接跳转"));

    // 清除本地 token 和用户信息
    localStorage.removeItem('authToken');
    localStorage.removeItem('userPhone');

    // 保存邀请信息，用于登录后自动处理
    localStorage.setItem('pendingInvitation', token);
    localStorage.setItem('intendedRecipient', intendedRecipient);

    // 跳转到登录页面
    window.location.href = '/';
    }

    function switchAccount() {
        // 清除当前登录信息
        fetch('/api/auth/logout', { method: 'POST' })
            .then(() => {
                localStorage.clear();
                redirectToLogin();
            });
    }

    function acceptInvitation() {
        fetch('/api/invitations/accept', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('authToken')
            },
            body: JSON.stringify({ token: token })
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            }
            throw new Error('网络请求失败');
        })
        .then(result => {
            if (result.success) {
                alert('邀请接受成功！');
                window.location.href = '/#my-received';
            } else {
                alert('接受失败: ' + result.message);
            }
        })
        .catch(error => {
            alert('网络错误: ' + error.message);
        });
    }

    function ignoreInvitation() {
        window.location.href = '/';
    }
    /*]]>*/
</script>
</body>
</html>